Flexbox and Grid what’s the difference

Yel Mangok John
Yel Mangok John

Tue, 17 Mar 2026

codecamp



Explain Flexbox properties (display:flex, justify-content, align-items) and build a responsive layout example. Explain grid containers, rows, columns, and create a simple layout using CSS Grid.


1. display: flex

This turns a container into a flex container.


.container {

  display: flex;

}


All direct children become flex items

Default direction is row


2. justify-content


Controls alignment horizontally (by default)


.container {

  display: flex;

  justify-content: center;

}


Common values use in flex:


flex-start → left

flex-end → right

center → center

space-between → space between items

space-around → space around items

space-evenly → equal spacing


3. align-items


Controls alignment vertically (by default)


.container {

  display: flex;

  align-items: center;

}

Common values:


stretch (default)

flex-start

flex-end

center




A responsive card layout that stacks on small screens and aligns in a row on larger screens.

HTML

<div class="container">

  <div class="box">1</div>

  <div class="box">2</div>

  <div class="box">3</div>

</div>


CSS

.container {

  display: flex;

  flex-wrap: wrap;

  justify-content: center;

  gap: 10px;

}


.box {

  background: steelblue;

  color: white;

  padding: 20px;

  flex: 1 1 200px;

  text-align: center;

}



🔹 CSS Grid Basics

1. Grid Container

.container {

  display: grid;

}


2. Rows and Columns


.container {

  display: grid;

  grid-template-columns: 1fr 1fr 1fr; /* 3 columns */

  grid-template-rows: auto;

}


🧩 Simple CSS Grid Layout Example


A basic page layout (header, sidebar, content, footer)

HTML:

<div class="container">

  <header>Header</header>

  <aside>Sidebar</aside>

  <main>Main Content</main>

  <footer>Footer</footer>

</div>


CSS:

.container {

  display: grid;

  grid-template-columns: 1fr 3fr;

  grid-template-rows: auto auto auto;

  gap: 10px;

}


header {

  grid-column: 1 / 3; /* span full width */

  background: #333;

  color: white;

  padding: 20px;

}


aside {

  background: #ccc;

  padding: 20px;

}


main {

  background: #eee;

  padding: 20px;

}


footer {

  grid-column: 1 / 3;

  background: #333;

  color: white;

  padding: 20px;

}



Flexbox vs Grid

Flexbox:


Best for components

Example: navbar, buttons, cards


Grid:

Best for page layout

Example: full website structure


Use them together:


/* Grid for layout */

.page {

  display: grid;

}


/* Flexbox inside components */

.nav {

  display: flex;

}

Share this article

Comments

0
?
0 / 2000
Loading comments…